<?php
/**
 * Created by b17
 * 2/23/12 5:43 PM
 */

namespace Managers\Widget;

class PollWidget extends AbstractWidget
{
    public function init()
    {
        $this->callPortedCode();
    }

    /**
     * Портированный код Виталика
     */
    private function callPortedCode()
    {
        $pollManager = new \Managers\PollVotingHistory();
        $longIP = ip2long(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1');

        $active_poll = $pollManager->getActivePollId();
        if (!$active_poll) {
            print_r("No active polls");
            return;
        }


        $array = array();
        foreach ($active_poll as $apoll) {
            $p = array_sum($apoll);

            if (!isset($_COOKIE["poll_id_" . $p])) {
                $data = $apoll['id'];
                $array[] = $data;
            }
        }
        $array2 = array();
        foreach ($array as $apoll2) {

            $checkIP = $pollManager->checkIP($longIP, $apoll2);
            //            die('Ok');
            if (!$checkIP) {
                $data = $apoll2;
                $array2[] = $data;
            }
        }

        if (empty($array2)) {

            $array2 = $active_poll;

            $random_key = array_rand($array2, 1);
            $randome_poll_id = $array2[$random_key];

            $poll_id = array_sum($randome_poll_id);

            $poll = $pollManager->getQuestion($poll_id);
            $poll_name = $poll['name'];
            $answers = $pollManager->getAnswersByPoolId($poll_id);

            $sum_count = 0;
            foreach ($answers as $count) {
                $sum_count = $sum_count * 1 + ($count['votesCount'] * 1);
            }

            $this->view->sum_count = $sum_count;
            $this->view->poll_name = $poll_name;
            $this->view->answers = $answers;
            return;
        }
        $random_key = array_rand($array2, 1);
        $randome_poll_id = $array2[$random_key];

        $poll_id = $randome_poll_id;
        $poll = $pollManager->getQuestion($poll_id);
        $answers = $pollManager->getAnswersByPoolId($poll_id);
        $poll_name = $poll['name'];


        $this->view->answers = $answers;
        $this->view->poll_name = $poll_name;
    }

    /**
     * Название файла для вывода.
     *
     */
    public function getScriptName()
    {
        return "/widget/poll.phtml";
    }
}
